package com.test.resumeanalysis.ui.home

import android.widget.Toast
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.setruth.mvvmbaseproject.network.ApiResponse
import com.setruth.mvvmbaseproject.network.api.JobInfoApi
import com.setruth.mvvmbaseproject.network.api.ResumeParseApi
import com.test.resumeanalysis.R
import com.test.resumeanalysis.common.BaseVBFragment
import com.test.resumeanalysis.data.model.JobInfo
import com.test.resumeanalysis.data.model.JobPost
import com.test.resumeanalysis.databinding.FragmentHomeBinding
import com.test.resumeanalysis.util.LogUtil
import com.test.resumeanalysis.viewModel.PublicViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext


class HomeFragment : BaseVBFragment<FragmentHomeBinding>(FragmentHomeBinding::inflate) {

    private val model: PublicViewModel by activityViewModels()
    lateinit var adapter: HomeAdapter
    lateinit var jobList: ArrayList<JobInfo>
    override fun initView() {
        super.initView()
        setHasOptionsMenu(true)
        setupToolbar(binding.homeToolbar, false)
        binding.homeToolbar.title = "职位"

        adapter = HomeAdapter()
        jobList = ArrayList()

        binding.homeRv.adapter = adapter
        val layoutManager = LinearLayoutManager(activity)
        binding.homeRv.layoutManager = layoutManager

        adapter.setOnItemClickListener(object : HomeAdapter.OnItemClickListener {
            override fun onItemClick(position: Int) {
                model.selectPost(jobList[position])
                findNavController().navigate(R.id.postInfoFragment)
            }
        })
        initWeb()
    }


    fun initWeb() {

        model.apply {
            request(JobInfoApi::class.java).getAllJob().getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e("${it.errMsg} ${it.exception}")
                            Toast.makeText(activity, "服务器未启动", Toast.LENGTH_LONG).show()
                        }
                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            it.data?.data?.let { it1 -> jobList.addAll(it1) }
                            withContext(Dispatchers.Main) {
                                adapter.data = jobList
                            }
                        }
                    }
                }
            }
        }

    }


}